package com.example.service;

import com.example.POJO.User;
import com.example.mapper.AccountMapper;
import com.example.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;

@Service
public class UserService {
    public void insertUser(User user) throws IOException {
        String resource= "mybatis-config.xml";
        InputStream inputStream= Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession=sqlSessionFactory.openSession(true);

        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
        userMapper.insertUser(user);

        sqlSession.close();
    }

    public User getUserById(Integer id) throws IOException {
        String resource= "mybatis-config.xml";
        InputStream inputStream= Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession=sqlSessionFactory.openSession(true);

        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
        User user=userMapper.getUserById(id);

        sqlSession.close();
        return user;
    }

    public void updateUser(User user) throws IOException {
        String resource= "mybatis-config.xml";
        InputStream inputStream= Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession=sqlSessionFactory.openSession(true);

        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
        userMapper.updateUser(user);

        sqlSession.close();
    }
}
